﻿
using System.Web.UI;
using AB.ServiceDirectory.Design.WebUserControls.Frame;

namespace AB.ServiceDirectory.Design.Org
{
    using System;
    using System.Linq;
    using System.Web.UI.WebControls;
    using BO;
    using Entities;

    /// <summary>
    /// Add Organisation class
    /// </summary>
    public partial class OrganisationDetails : System.Web.UI.Page
    {
        #region Events
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadCountries();
                LoadReferenceData();
                LoadOrganisation();
                LoadOrganisationPrograms();

            }

            LoadSupportingMaterialFrame();
            LoadDirectorateFrame();
            InitPostBackControlValues();
        }

        /// <summary>
        /// Handles the Command event of the ButtonLookup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonLookup_Command(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "contact":
                    ContactLookupPopup.Popup();
                    break;

                case "postcode":
                    AddressLookupPopup.Popup();
                    break;

                case "business":
                    BusinessLookup.Popup();
                    break;
            }
        }

        /// <summary>
        /// Handles the Click event of the ButtonSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonSave_Command(object sender, CommandEventArgs e)
        {
            // Initialize Organisation object
            var organisation = new Organisation();
            organisation.OrganisationName = TextBoxOrganisationName.Text;

            // Check is name exists
            if (!organisation.OrganisationName.Equals(HiddenFieldOrganisationName.Value) &&
                OrganisationBO.IsNameExists(organisation.OrganisationName))
            {
                LabelNameExists.Text = "Organisation name must be unique";
                return;
            }

            //string str = "Are you sure, you want to Approve this Record?";
            
            //ClientScript.RegisterStartupScript(typeof(Page), "Confirm", "ConfirmApproval('" + str + "');", true);

            //return;
            // Assign other value to the object properties
            if (ButtonSave.CommandName.Equals("edit"))
            {
                int organisationId;
                organisation.OrganisationId = int.TryParse(HiddenFieldOrganisationId.Value, out organisationId) ? organisationId : 0;
            }

            organisation.ShortDescription = TextBoxShortDescription.Text;
            organisation.FullDescription = TextBoxFullDescription.Text;
            organisation.CityTown = TextBoxCityTown.Text;
            organisation.County = TextBoxCounty.Text;
            organisation.PreferredOrganisation = CheckBoxPreferredOrganisation.Checked;
            organisation.PhoneNumber = TextBoxPhoneNumber.Text;
            organisation.Fax = TextBoxFax.Text;
            organisation.Email = TextBoxEmail.Text;
            organisation.WebAddress = TextBoxWebAddress.Text;
            organisation.CharityNumber = TextBoxCharityNumber.Text;
            organisation.CompanyNumber = TextBoxCompanyNumber.Text;
            //organisation.IsActive = ButtonInactive.CommandName.Equals("active");
            organisation.CountryId = DropDownListNationCounty.SelectedValue;

            // Hidden fields
            int contactId;
            organisation.ContactId = int.TryParse(HiddenFieldContactId.Value, out contactId)
                                        ? contactId : (int?)null;
            organisation.BusinessId = int.Parse(HiddenFieldBusinessId.Value);
            organisation.AddressId = int.Parse(HiddenFieldAddressId.Value);

            // Reference details
            var specialism = string.Join("-", CheckBoxListOrgSpecialism.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var disabilities = string.Join("-", CheckBoxListDisabilities.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var barriers = string.Join("-", CheckBoxListBarriers.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var benefits = string.Join("-", CheckBoxListBenefits.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var circumstances = string.Join("-", CheckBoxListCircumstances.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var ethnicity = string.Join("-", CheckBoxListEthnicity.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var accreditation = string.Join("-", CheckBoxListAccreditation.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            organisation.OrganisationSpecialism = specialism;
            organisation.ServiceDisabilities = disabilities;
            organisation.ServiceBarriers = barriers;
            organisation.ServiceBenefits = benefits;
            organisation.ServiceCircumstances = circumstances;
            organisation.ServiceEthnicity = ethnicity;
            organisation.Accreditation = accreditation;

            var savedResult = ButtonSave.CommandName.Equals("new")
                                  ? OrganisationBO.AddOrganisation(organisation)
                                  : OrganisationBO.EditOrganisation(organisation);

            // Add organisation
            if (!savedResult)
            {
                DialogBox.Error("Save organisation failed");
                return;
            }

            // Expression of Interest
            if (CheckBoxInterest.Checked)
            {
                var organisationPrograms = CheckBoxListPrograms.Items.Cast<ListItem>().Where(c => c.Selected).Select(
                    c => new OrganisationProgram { OrganisationId = organisation.OrganisationId, ProgramId = int.Parse(c.Value) }).ToList();
                if (ButtonSave.CommandName.Equals("new"))
                {
                    OrganisationBO.AddOrganisationProgram(organisationPrograms);
                }
                else
                {
                    OrganisationBO.EditOrganisationProgarm(organisation.OrganisationId, organisationPrograms);
                }
            }

            if (ButtonSave.CommandName.Equals("new"))
            {
                LoadDirectorateFrame();
            }

            // Set the control values after add organisation
            ButtonSave.CommandName = "edit";
            ButtonInactive.Visible = true;
            HiddenFieldOrganisationId.Value = organisation.OrganisationId.ToString();
            HiddenFieldOrganisationName.Value = organisation.OrganisationName;

            // Show inform message to screen
            DialogBox.Success("Save organisation successfully.");

        }

        /// <summary>
        /// Handles the CheckedChanged event of the CheckBoxInterest control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void CheckBoxInterest_CheckedChanged(object sender, EventArgs e)
        {
            LinkDetails03.Visible = CheckBoxInterest.Checked;
            DetailsPanel03.Visible = CheckBoxInterest.Checked;

            LoadExpressionOfInterest();
        }

        /// <summary>
        /// Handles the Command event of the ButtonInactive control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonInactive_Command(object sender, CommandEventArgs e)
        {
            SetInactiveButtonMode(e.CommandName);
        }
        #endregion

        #region Methods
        /// <summary>
        /// Loads the edited organisation.
        /// </summary>
        private void LoadOrganisation()
        {
            int organisationId;
            if (!int.TryParse(Request.Params["id"], out organisationId))
            {
                return;
            }

            var organisation = OrganisationBO.GetOrganisation(organisationId);
            if (organisation != null)
            {
                TextBoxOrganisationName.Text = organisation.OrganisationName;
                TextBoxShortDescription.Text = organisation.ShortDescription;
                TextBoxFullDescription.Text = organisation.FullDescription;
                if (organisation.Contact != null)
                {
                    TextBoxLeadContact.Text = string.Format("{0} {1}", organisation.Contact.FirstName,
                                                        organisation.Contact.Surname);
                }

                TextBoxAddressLine1.Text = organisation.Address.AddressLine;
                TextBoxAddressLine2.Text = organisation.Address.AddressLine2;
                TextBoxAddressLine3.Text = organisation.Address.AddressLine3;
                TextBoxPostcode.Text = organisation.Address.Postcode;
                TextBoxCityTown.Text = organisation.CityTown;
                TextBoxCounty.Text = organisation.County;
                CheckBoxPreferredOrganisation.Checked = organisation.PreferredOrganisation != null
                                                            ? organisation.PreferredOrganisation.Value
                                                            : false;
                TextBoxTypeOfBusiness.Text = organisation.BusinessType.BusinessName;
                TextBoxSicCode.Text = organisation.BusinessType.SICCode;
                TextBoxPhoneNumber.Text = organisation.PhoneNumber;
                TextBoxFax.Text = organisation.Fax;
                TextBoxEmail.Text = organisation.Email;
                TextBoxWebAddress.Text = organisation.WebAddress;
                TextBoxCharityNumber.Text = organisation.CharityNumber;
                TextBoxCompanyNumber.Text = organisation.CompanyNumber;
                ButtonInactive.CommandName = organisation.IsActive ? "active" : "deactive";
                DropDownListNationCounty.SelectedValue = organisation.CountryId;

                HiddenFieldAddressId.Value = organisation.AddressId.ToString();
                HiddenFieldBusinessId.Value = organisation.BusinessId.ToString();
                HiddenFieldContactId.Value = organisation.ContactId.ToString();
                HiddenFieldOrganisationId.Value = organisation.OrganisationId.ToString();
                HiddenFieldOrganisationName.Value = organisation.OrganisationName;

                string[] specialism = (organisation.OrganisationSpecialism ?? string.Empty).Split('-');
                string[] disabilities = (organisation.ServiceDisabilities ?? string.Empty).Split('-');
                string[] barriers = (organisation.ServiceBarriers ?? string.Empty).Split('-');
                string[] benefits = (organisation.ServiceBenefits ?? string.Empty).Split('-');
                string[] circumstances = (organisation.ServiceCircumstances ?? string.Empty).Split('-');
                string[] ethnicity = (organisation.ServiceEthnicity ?? string.Empty).Split('-');
                string[] accreditation = (organisation.Accreditation ?? string.Empty).Split('-');


                SetSelectedItemsInCheckBoxList(specialism, CheckBoxListOrgSpecialism);
                SetSelectedItemsInCheckBoxList(disabilities, CheckBoxListDisabilities);
                SetSelectedItemsInCheckBoxList(barriers, CheckBoxListBarriers);
                SetSelectedItemsInCheckBoxList(benefits, CheckBoxListBenefits);
                SetSelectedItemsInCheckBoxList(circumstances, CheckBoxListCircumstances);
                SetSelectedItemsInCheckBoxList(ethnicity, CheckBoxListEthnicity);
                SetSelectedItemsInCheckBoxList(accreditation, CheckBoxListAccreditation);

                ButtonSave.CommandName = "edit";
                SetInactiveButtonMode(organisation.IsActive ? "deactive" : "active");

                LinkDetails04.Visible = true;
                DetailsPanel04.Visible = true;
            }
        }

        /// <summary>
        /// Loads the organisation programs.
        /// </summary>
        private void LoadOrganisationPrograms()
        {
            int organisationId;
            if (int.TryParse(HiddenFieldOrganisationId.Value, out organisationId))
            {
                var data = OrganisationBO.GetOrganisationProgramByOrganisatonId(organisationId).Select(o => o.ProgramId).ToList();
                if (data.Count <= 0)
                {
                    return;
                }

                CheckBoxInterest.Checked = true;
                LinkDetails03.Visible = true;
                DetailsPanel03.Visible = true;
                LoadExpressionOfInterest();

                foreach (ListItem item in CheckBoxListPrograms.Items)
                {
                    if (data.Contains(int.Parse(item.Value)))
                    {
                        item.Selected = true;
                    }
                }
            }
        }

        /// <summary>
        /// Loads the countries.
        /// </summary>
        private void LoadCountries()
        {
            DropDownListNationCounty.DataSource = CountryBO.GetCountries();
            DropDownListNationCounty.DataBind();
        }

        /// <summary>
        /// Loads the reference data.
        /// </summary>
        private void LoadReferenceData()
        {
            CheckBoxListOrgSpecialism.DataSource = OrganisationBO.GetReferencesByCategoryId(1);
            CheckBoxListOrgSpecialism.DataBind();

            CheckBoxListDisabilities.DataSource = OrganisationBO.GetReferencesByCategoryId(2);
            CheckBoxListDisabilities.DataBind();

            CheckBoxListBarriers.DataSource = OrganisationBO.GetReferencesByCategoryId(3);
            CheckBoxListBarriers.DataBind();

            CheckBoxListBenefits.DataSource = OrganisationBO.GetReferencesByCategoryId(4);
            CheckBoxListBenefits.DataBind();

            CheckBoxListCircumstances.DataSource = OrganisationBO.GetReferencesByCategoryId(5);
            CheckBoxListCircumstances.DataBind();

            CheckBoxListEthnicity.DataSource = OrganisationBO.GetReferencesByCategoryId(6);
            CheckBoxListEthnicity.DataBind();

            CheckBoxListAccreditation.DataSource = OrganisationBO.GetReferencesByCategoryId(7);
            CheckBoxListAccreditation.DataBind();
        }

        /// <summary>
        /// Loads the expression of interest.
        /// </summary>
        private void LoadExpressionOfInterest()
        {
            var programBo = new ProgramBO();
            CheckBoxListPrograms.DataSource = programBo.GetProgramList(null, null, -1, -1);
            CheckBoxListPrograms.DataBind();
        }

        /// <summary>
        /// Loads the directorate frame.
        /// </summary>
        private void LoadDirectorateFrame()
        {
            int organisationId;
            if (int.TryParse(HiddenFieldOrganisationId.Value, out organisationId))
            {
                DetailsPanel06.Visible = true;
                LinkDetails06.Visible = true;

                var directorateFrame =
                    (DirectorateListFrame)Page.LoadControl("~/WebUserControls/Frame/DirectorateListFrame.ascx");
                directorateFrame.OrganisationId = organisationId;
                PlaceHolderDirectorate.Controls.Clear();
                PlaceHolderDirectorate.Controls.Add(directorateFrame);
            }
        }

        /// <summary>
        /// Loads the supporting material frame.
        /// </summary>
        private void LoadSupportingMaterialFrame()
        {
            int organisationId;
            if (int.TryParse(HiddenFieldOrganisationId.Value, out organisationId))
            {
                DetailsPanel05.Visible = true;
                LinkDetails05.Visible = true;

                var supportingMaterialListFrame =
                    (SupportingMaterialListFrame)Page.LoadControl("~/WebUserControls/Frame/SupportingMaterialListFrame.ascx");
                supportingMaterialListFrame.OrganisationId = organisationId;
                PlaceHolderSupportingMaterial.Controls.Clear();
                PlaceHolderSupportingMaterial.Controls.Add(supportingMaterialListFrame);
            }
        }

        /// <summary>
        /// Inits the default control value.
        /// </summary>
        private void InitPostBackControlValues()
        {
            LabelNameExists.Text = string.Empty;
        }

        /// <summary>
        /// Sets the inactive button mode.
        /// </summary>
        /// <param name="mode">The mode.</param>
        private void SetInactiveButtonMode(string mode)
        {
            var status = mode.Equals("active");
            int organisationId;
            if (!int.TryParse(HiddenFieldOrganisationId.Value, out organisationId))
            {
                return;
            }

            OrganisationBO.SetActiveOrganisation(organisationId, !status);
            ButtonInactive.Visible = true;
            ButtonInactive.CommandName = status ? "deactive" : "active";
            ButtonInactive.Text = status ? "Active" : "In-active";
        }

        /// <summary>
        /// Sets the selected items in check box list.
        /// </summary>
        /// <param name="selectedIds">The selected ids.</param>
        /// <param name="checkBoxList">The check box list.</param>
        private void SetSelectedItemsInCheckBoxList(string[] selectedIds, CheckBoxList checkBoxList)
        {
            foreach (ListItem item in checkBoxList.Items)
            {
                if (selectedIds.Contains(item.Value))
                {
                    item.Selected = true;
                }
            }
        }
        #endregion
    }
}